package com.drugStorage.hibernate.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.drugStorage.domain.SumDrugStorageList;
import com.drugStorage.hibernate.Utils.HibernateUtils;

public class SumDrugStorageListDaoImpl implements
		com.drugStorage.hibernate.dao.SumDrugStorageListDao {
	
	private static final String LOAD_ALL = "from SumDrugStorageList";

	private static final String GET_Sum_By_DrugId = "from SumDrugStorageList s where s.drug.id=?";
	public SumDrugStorageList findSumDrugStorageListById(int id) {
		Session s = null;

		try {
			s = HibernateUtils.getSession();

			Criteria c = s.createCriteria(SumDrugStorageList.class);
			c.add(Restrictions.eq("id", id));
			SumDrugStorageList sumDrugStorageList = (SumDrugStorageList) c.uniqueResult();
			return sumDrugStorageList;

		} finally {
			if (s != null)
				s.close();
		}
	}

	public SumDrugStorageList findSumDrugStorageListByName(String name) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<SumDrugStorageList> getSumDrugStorageLists() {
		Session s = null;
		try{
			s = HibernateUtils.getSession();
			Query q = s.createQuery(LOAD_ALL);
			return q.list();
		}finally{
			if(s!=null)
				s.close();
		}
	}

	public void saveSumDrugStorageList(SumDrugStorageList sumDrugStorageList) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtils.getSession();
			tx = s.beginTransaction();
			s.persist(sumDrugStorageList);
			tx.commit();
		} finally {
			if (s != null)
				s.close();

		}

	}

	public void updateSumDrugStorageList(SumDrugStorageList sumDrugStorageList) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtils.getSession();
			tx = s.beginTransaction();
			s.saveOrUpdate(sumDrugStorageList);
			tx.commit();
		} finally {
			if (s != null)
				s.close();

		}

	}

	public SumDrugStorageList getSumDrugStorageListByDrugID(int id) {
		
		Session s = null;
		try {
			s = HibernateUtils.getSession();
			Query q = s.createQuery(GET_Sum_By_DrugId);
              q.setParameter(0, id);
           SumDrugStorageList sumDrugStorageList =  (SumDrugStorageList) q.uniqueResult();
//              for(BuyList b:l){
//              Hibernate.initialize(b.getDrug().getName());
//              }
			return sumDrugStorageList;

		} finally {
			if (s != null)
				s.close();

		}
	}

}
